package filehandling;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import parser.AdventureParse;
import adventure.Adventure;

/**
 *
 * @author Michael Hanns
 *
 */
public class Saving {

    public static String savePrompt(Adventure a) {
        JFileChooser fc = new JFileChooser();

        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
            }

            @Override
            public String getDescription() {
                return "*.xml - eXtensible Markup Language file";
            }
        };

        fc.setFileFilter(filter);
        fc.setCurrentDirectory(new File(System.getProperty("user.dir") + "/modules/"));

        int returnVal = fc.showSaveDialog(null);

        String fileName = "";

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            fileName = fc.getSelectedFile().getAbsolutePath();
            // Add Jimer Markup Language extension..
            if (!fileName.toUpperCase().endsWith(".XML")) {
                fileName = fileName + ".xml";
            }
            return fileName;
        }
        return null;
    }
    
    public static boolean saveToFile(Adventure a, String filename) {
        if(filename == null) {
            return false;
        }
        File file = new File(filename);
        FileOutputStream out;
        PrintStream p;
        String witmlString = new AdventureParse().convertToXML(a);
        try {
            out = new FileOutputStream(file);

            p = new PrintStream(out);
            p.println(witmlString);
            p.close();

            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
